package com.ds.lens.data.service.dao;

import com.ds.lens.data.service.dao.entity.LensMonitorTags;
import com.ds.lens.data.service.dao.sql.provider.LensMonitorTagsSqlProvider;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface LensMonitorTagsDao {
    @Delete({
            "delete from lens_monitor_tags",
            "where monitor_id = #{id,jdbcType=BIGINT}"
    })
    int deleteByMonitorId(Long id);

    @Insert({"<script>", "insert into lens_monitor_tags (monitor_id, application_id, content)", "values ",
            "<foreach collection='tags' item='tag' separator=','>",
            "(#{tag.monitorId},#{tag.applicationId},#{tag.content})",
            "</foreach>", "</script>"})
    Long batchInsert(@Param("tags") List<LensMonitorTags> tags);

    @InsertProvider(type = LensMonitorTagsSqlProvider.class, method = "insertSelective")
    int insertSelective(LensMonitorTags record);

    @Select({
            "select",
            "id, monitor_id, application_id, content",
            "from lens_monitor_tags",
            "where id = #{id,jdbcType=BIGINT}"
    })
    @Results(id = "tagsMap", value = {
            @Result(column = "id", property = "id", jdbcType = JdbcType.BIGINT, id = true),
            @Result(column = "monitor_id", property = "monitorId", jdbcType = JdbcType.BIGINT),
            @Result(column = "application_id", property = "applicationId", jdbcType = JdbcType.BIGINT),
            @Result(column = "content", property = "content", jdbcType = JdbcType.VARCHAR)
    })
    LensMonitorTags selectByPrimaryKey(Long id);

    @UpdateProvider(type = LensMonitorTagsSqlProvider.class, method = "updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(LensMonitorTags record);

    @Update({
            "update lens_monitor_tags",
            "set monitor_id = #{monitorId,jdbcType=BIGINT},",
            "content = #{content,jdbcType=VARCHAR}",
            "where id = #{id,jdbcType=BIGINT}"
    })
    int updateByPrimaryKey(LensMonitorTags record);

    @Select({"select distinct content from lens_monitor_tags where application_id = #{applicationId,jdbcType=BIGINT}"})
    List<String> getAllTags(@Param("applicationId") Long applicationId);

    @Select({
            "<script>",
            "select",
            "id, monitor_id, application_id, content",
            "from lens_monitor_tags",
            "where application_id = #{applicationId,jdbcType=BIGINT} ",
            "<if test='tags != null and tags.size > 0'> and content in ",
            "<foreach collection='tags' item='tag' separator=',' open='(' close=')'>",
            "#{tag}",
            "</foreach>",
            " </if>",
            "</script>"
    })
    @ResultMap("tagsMap")
    List<LensMonitorTags> queryByTags(@Param("tags") List<String> tags,
                                      @Param("applicationId") Long applicationId);
}
